﻿using KPIS.GERP.Models.Class;
using KPIS.GERP.Models.ICM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class MovementController : Controller
    {
        public ActionResult Index()
        {
            var service = new MovementService.MovementServiceClient();

            return View(service.Select(new Models.ICM.Movement { RecordStatus = "!D" }, new[] { "MasResourceType", "SourceWarehouse", "DestinationJobSite", "DestinationWarehouse" }));
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Movement m)
        {
            if (ModelState.IsValid)
            {
                var service = new MovementService.MovementServiceClient();
                int id = service.Insert(m, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("Index", new { id = id });
            }
            return View(m);
        }

        public ActionResult Edit(int id)
        {
            var service = new MovementService.MovementServiceClient();
            var model = service.Select(new Models.ICM.Movement { MovementId = id }, null).FirstOrDefault();

            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(int id, Movement model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    model.UpdatedWhen = DateTime.Now;

                    var service = new MovementService.MovementServiceClient();
                    service.Update(model, Class.GimsMembership.CurrentEmpId);

                    return RedirectToAction("Index");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return View();
        }

        public ActionResult Details(int id)
        {
            var service = new MovementService.MovementServiceClient();
            var model = service.Select(new Models.ICM.Movement { MovementId = id }, new[] { "MasResourceType", "SourceWarehouse", "DestinationJobSite", "DestinationWarehouse" }).FirstOrDefault();

            return View(model);
        }

        public ActionResult Delete(int id, MovementDtl model)
        {
            var service = new MovementService.MovementServiceClient();
            try
            {
                var MovementDetailList = service.SelectMovementDtl(new Models.ICM.MovementDtl() { RecordStatus = "!D", MovementId = id, MovementDtlId = model.MovementDtlId }, null);
                
                if(MovementDetailList.Length > 0 ){

                    ModelState.AddModelError("Duplicate", "!มีรายการโอนย้าย กรุณาตรวจสอบอีกครั้ง");
                    return View("Index", service.Select(new Models.ICM.Movement { RecordStatus = "!D" }, null));
                }
                else{
                    service.Delete(id, Class.GimsMembership.CurrentEmpId);
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View("Index");
            }
        }

        public ActionResult DeleteAll(int[] deleteIds)
        {
            var service = new MovementService.MovementServiceClient();
            try
            {
                if (deleteIds != null)
                {
                    foreach (int delete in deleteIds)
                    {
                        var MovementDetailList = service.SelectMovementDtl(new MovementDtl() { RecordStatus = "!D", MovementId = delete }, null);

                        if (MovementDetailList.Length > 0)
                        {
                            ModelState.AddModelError("Duplicate", "!มีรายการโอนย้าย กรุณาตรวจสอบอีกครั้ง");
                            return View("Index", service.Select(new Models.ICM.Movement { RecordStatus = "!D" }, null));
                        }
                        else if (MovementDetailList.Length == 0)
                        {
                            service.Delete(delete, Class.GimsMembership.CurrentEmpId);
                        }
                    }
                }

                ModelState.AddModelError("Error", "ลบข้อมูลไปทั้งหมด " + deleteIds.Length.ToString("#,##0") + " รายการ");

                return Json(new { success = true });
            }
            catch
            {
                ModelState.AddModelError("Error", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false });
            }
        }

        #region MovementDtl

        public ActionResult IndexMovementDtl(int MovementId)
        {
            var service = new MovementService.MovementServiceClient();

            ViewBag.MovementId = MovementId;

            return View(service.SelectMovementDtl(new MovementDtl { RecordStatus = "!D", MovementId = MovementId }, new[] { "Asset" }));
        }

        public ActionResult CreateMovementDtl(int MovementId)
        {
            var service = new MovementService.MovementServiceClient();

            var modelMovement = service.Select(new Models.ICM.Movement { MovementId = MovementId}, null).FirstOrDefault();
            var model = new MovementDtl();

            model.MovementId = modelMovement.MovementId;
            model.Movement = modelMovement;
           // ViewBag.modelMovement = modelMovement;

            return View(model);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult CreateMovementDtl(MovementDtl model, int MovementId)
        {
            var service = new MovementService.MovementServiceClient();
            var serviceAsset = new AssetService.AssetServiceClient();
            var serviceWarehouse = new WarehouseService.WarehouseServiceClient();
            var modelMovement = service.Select(new Models.ICM.Movement { MovementId = model.MovementId ?? 0 }, new[] { "SourceWarehouse", "DestinationWarehouse", "JobSite" }).FirstOrDefault();
            var modelAsset = serviceAsset.SelectAsset(new Asset { AssetId = model.AssetId }, null).FirstOrDefault();
            MovementHistory modelMoveHistory = new MovementHistory();
            ViewBag.MovementId = model.MovementId;

            if (ModelState.IsValid)
            {
                try
                {
                    var MovementDetailList = service.SelectMovementDtl(new MovementDtl() { RecordStatus = "!D", MovementId = model.MovementId }, null);

                    foreach (var MovementDetail in MovementDetailList)
                    {
                        if (MovementDetail.AssetId == model.AssetId)
                        {
                            model.Movement = modelMovement;
                            ModelState.AddModelError("", "!เกิดข้อผิดพลาด รายการพัสดุนี้มีอยู่แล้ว");
                            return View("IndexMovementDtl", service.SelectMovementDtl(new MovementDtl { RecordStatus = "!D", MovementId = MovementId}, new[] { "Asset" }));
                        }
                    }

                    if (modelMovement.MoveMethod == 1)
                    {
                       //Insert MovementHistory
                        modelMoveHistory.AssetId = model.AssetId;
                        modelMoveHistory.SourceLocation = modelMovement.SourceWarehouse.Name;
                        modelMoveHistory.DestinationLocation = modelMovement.DestinationWarehouse.Name;
                        modelMoveHistory.MoveRefNo = modelMovement.MovementId;
                        modelMoveHistory.MoveQty = 1;   // model.MoveQty;
                        modelMoveHistory.MovementType = "Move";
                    }
                    else if (modelMovement.MoveMethod == 2)
                    {
                        //Insert MovementHistory
                        modelMoveHistory.AssetId = model.AssetId;
                        modelMoveHistory.SourceLocation = modelMovement.SourceJobSite.Name;
                        modelMoveHistory.DestinationLocation = modelMovement.DestinationWarehouse.Name;
                        modelMoveHistory.MoveRefNo = modelMovement.MovementId;
                        modelMoveHistory.MoveQty = 1;   // model.MoveQty;
                        modelMoveHistory.MovementType = "Move";
                    }

                    //Update Asset
                    modelAsset.JobSiteId = null;
                    modelAsset.WhId = modelMovement.DestinationWarehouseId ?? 0;
                    modelAsset.Place = serviceWarehouse.Select(new Warehouse() { WhId = modelMovement.DestinationWarehouseId ?? 0 }, null).FirstOrDefault().Name;

                    serviceAsset.UpdateMovementAsset(modelAsset, Class.GimsMembership.CurrentEmpId);
                    service.InsertMovementHistory(modelMoveHistory, Class.GimsMembership.CurrentEmpId);
                    model.MoveQty = 1;
                    int id = service.InsertMovementDtl(model, Class.GimsMembership.CurrentEmpId);
                    return RedirectToAction("IndexMovementDtl", new { MovementId = model.MovementId});
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("Duplicate", ex.Message);
                    return View(model);
                }
            }
            return View(model);
        }

        public ActionResult EditMovementDtl(int id)
        {
            var service = new MovementService.MovementServiceClient();
            var model = service.SelectMovementDtl(new Models.ICM.MovementDtl { MovementDtlId = id }, null).FirstOrDefault();
            var modelMovement = service.Select(new Movement() { MovementId = model.MovementId ?? 0 }, null).FirstOrDefault();
            model.Movement = modelMovement;

            return View(model);
        }

        [HttpPost]
        public ActionResult EditMovementDtl(int id, int movementId, int assetId, MovementDtl model)
        {
            var service = new MovementService.MovementServiceClient();
            var serviceAsset = new AssetService.AssetServiceClient();
            var serviceWarehouse = new WarehouseService.WarehouseServiceClient();

            var oldAssetId = service.SelectMovementDtl(new MovementDtl() { MovementDtlId = model.MovementDtlId }, null).FirstOrDefault().AssetId;
            var oldMovementDtlId = model.MovementDtlId;
            var oldMovementId = model.MovementId;
            //var oldMovementDtlId = service.SelectMovementDtl(new MovementDtl() { MovementDtlId = model.MovementDtlId }, null).FirstOrDefault().MovementDtlId;
            //var oldMovementId = service.SelectMovementDtl(new MovementDtl() { MovementDtlId = model.MovementDtlId }, null).FirstOrDefault().MovementId;

            var modelMovement = service.Select(new Movement() { MovementId = model.MovementId ?? 0 }, null).FirstOrDefault();

            if (ModelState.IsValid)
            {
                try
                {
                    if (oldAssetId == assetId && oldMovementId == movementId && oldMovementDtlId == id)
                    {
                        service.UpdateMovementDtl(model, Class.GimsMembership.CurrentEmpId);
                        var modelAsset = serviceAsset.SelectAsset(new Asset { AssetId = assetId }, null).FirstOrDefault();

                        //Update Asset
                        modelAsset.JobSiteId = null;
                        modelAsset.WhId = modelMovement.DestinationWarehouseId ?? 0;
                        modelAsset.Place = serviceWarehouse.Select(new Warehouse() { WhId = modelMovement.DestinationWarehouseId ?? 0 }, null).FirstOrDefault().Name;

                        serviceAsset.UpdateMovementAsset(modelAsset, Class.GimsMembership.CurrentEmpId);
                    }
                    else
                    {
                        model.Movement = modelMovement;
                        ModelState.AddModelError("Error", "!เกิดข้อผิดพลาด ข้อมูลนี้มีบันทึกอยู่แล้ว");
                    }
                }
                catch (Exception ex)
                {
                    model.Movement = modelMovement;
                    ModelState.AddModelError("Duplicate", ex.Message);
                    return View(model);
                }
            }
            return View(model);
        }

        public ActionResult DeleteMovementDtl(int id, int movementId)
        {
            var service = new MovementService.MovementServiceClient();
            MovementHistory modelMoveHistory = new MovementHistory();

            try
            {
                var MovementHis = service.SelectMovementHistory(new Models.ICM.MovementHistory() { RecordStatus = "!D", MoveRefNo = movementId }, null).FirstOrDefault().MoveHistId;

                service.DeleteMovementHistory(MovementHis, Class.GimsMembership.CurrentEmpId);
                service.DeleteMovementDtl(id, Class.GimsMembership.CurrentEmpId);

                return RedirectToAction("IndexMovementDtl", new { MovementId = movementId });
            }
            catch
            {
                return View("IndexMovementDtl", new { MovementId = movementId });
            }
        }

        public ActionResult DeleteAllMovementDtl(int[] deleteIds)
        {
            try
            {
                if (deleteIds != null)
                {
                    var service = new MovementService.MovementServiceClient();

                    foreach (int delete in deleteIds)
                    {
                        service.DeleteMovementDtl(delete, Class.GimsMembership.CurrentEmpId);
                    }
                }

                ModelState.AddModelError("Error", "ลบข้อมูลไปทั้งหมด " + deleteIds.Length.ToString("#,##0") + " รายการ");

                return Json(new { success = true });
            }
            catch
            {
                ModelState.AddModelError("Error", "พบข้อผิดพลาดขณะลบข้อมูล");
                return Json(new { success = false });
            }

        }

        public ActionResult AssetUnit(int assetId)
        {
            Asset model = null;
            var service = new AssetService.AssetServiceClient();

            try
            {
                model = service.SelectAsset(new Models.ICM.Asset { AssetId = assetId, RecordStatus = "!D" }, new[] { "MasUnit" }).FirstOrDefault();
            }
            catch (Exception e)
            {
                throw e;
            }
            return Json(new { Quantity = model.Quantity, Description = model.Description, UnitName = model.MasUnit.Name }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DupicateAssetId(int assetId)
        {
           var service = new  MovementService.MovementServiceClient();
           return View(service.SelectMovementDtl(new Models.ICM.MovementDtl { AssetId = assetId, RecordStatus = "!D" },null).FirstOrDefault().AssetId);
        }


        public ActionResult MasUnit()
        {
            MasUnit model = null;
            try
            {
                var service = new MasUnitService.MasUnitServiceClient();

                model = service.SelectMasUnit(new Models.ICM.MasUnit { RecordStatus = "!D" }, null).FirstOrDefault();
            }
            catch (Exception e)
            {
                throw e;
            }
            return Json(new { UnitId = model.Name }, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region Report

        public void MovementDtlsReport(int movementId)
        {
            var service = new MovementService.MovementServiceClient();
            var model = service.MovementReportHead(movementId);
            MailMerge mailMerge = new MailMerge();
            Dictionary<string, string> fields = new Dictionary<string, string>();
            var dics = service.MovementReportDtls(movementId).ToList();

            fields.Add("EmpName", model[0]);
            fields.Add("PosName", model[1]);
            fields.Add("JobSiteName", model[2]);
            fields.Add("SubJobSiteName", model[3]);
            fields.Add("MovementCode", model[4]);

            string strTemplatePath = Server.MapPath("~/Templates/ใบส่งคืนพัสดุ.docx");
            string strSaveAsPath = Server.MapPath("~/Temp/");
            string strSaveAsFileName = string.Format("ใบส่งคืนพัสดุ{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmssffff"));

            if (mailMerge.MergeTemplate(strTemplatePath, strSaveAsPath + strSaveAsFileName, fields, null, dics, null))
            {
                Response.Clear();
                Response.ContentType = "text/plain";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + strSaveAsFileName);
                Response.WriteFile(strSaveAsPath + strSaveAsFileName);
                Response.Flush();
                if (true)
                {
                    System.IO.File.Delete(strSaveAsPath + strSaveAsFileName);
                }
                Response.End();
            }
        }
        #endregion
    }
}

